import type { PaymentRecord } from '@/services/database'

// 基于 localStorage 的持久化 Mock 仓库
const STORAGE_KEY_PREFIX = 'mock_payments_' // 每个会员单独一份

function readFromStorage(memberId: string): PaymentRecord[] {
    try {
        const raw = localStorage.getItem(STORAGE_KEY_PREFIX + memberId)
        if (!raw) return []
        const list = JSON.parse(raw) as PaymentRecord[]
        return Array.isArray(list) ? list : []
    } catch {
        return []
    }
}

function writeToStorage(memberId: string, records: PaymentRecord[]): void {
    localStorage.setItem(STORAGE_KEY_PREFIX + memberId, JSON.stringify(records))
}

// 初始化默认数据（仅在本地没有记录时）
function ensureDefaults() {
    const id10001 = '10001'
    if (readFromStorage(id10001).length === 0) {
        const init: PaymentRecord = {
            id: 'MOCK_INIT_10001_1',
            member_id: id10001,
            payment_type: 'recharge',
            amount: '8888',
            balance: '¥8,888',
            currency: 'JPY',
            payment_channel: '扫码充值',
            remark: '初始充值（Mock）',
            status: 'success',
            payment_date: new Date('2025-06-01 08:30:15').toLocaleString(),
            transaction_id: 'MOCK_TXN_10001_1',
            create_time: new Date('2025-06-01 08:30:15').toLocaleString(),
            operator: '系统',
            related_record_id: '',
            is_revoked: 0
        }
        writeToStorage(id10001, [init])
    }
    const id10003 = '10003'
    if (readFromStorage(id10003).length === 0) {
        const init3: PaymentRecord = {
            id: 'MOCK_INIT_10003_1',
            member_id: id10003,
            payment_type: 'recharge',
            amount: '1000',
            balance: '¥1,000',
            currency: 'JPY',
            payment_channel: '好友转账',
            remark: '来自用户1',
            status: 'success',
            payment_date: new Date('2025-06-05 10:00:00').toLocaleString(),
            transaction_id: 'MOCK_TXN_10003_1',
            create_time: new Date('2025-06-05 10:00:00').toLocaleString(),
            operator: '系统',
            related_record_id: '',
            is_revoked: 0
        }
        writeToStorage(id10003, [init3])
    }
}

ensureDefaults()

export function getMockPaymentRecords(memberId: string): PaymentRecord[] {
    return readFromStorage(memberId)
}

export function setMockPaymentRecords(memberId: string, records: PaymentRecord[]): void {
    writeToStorage(memberId, records)
}

export function addMockPaymentRecord(memberId: string, record: PaymentRecord): string {
    const list = readFromStorage(memberId)
    list.push(record)
    writeToStorage(memberId, list)
    return record.id
}

export function generateMockId(prefix: string = 'MOCK'): string {
    return `${prefix}_${Date.now()}_${Math.floor(Math.random() * 100000)}`
}


